'use strict';

const {formatDate, formatAmount} = require("../../utils/format");
module.exports = app => {
  const { STRING, INTEGER, DATE, TEXT, DECIMAL } = app.Sequelize;

  const Product = app.model.define('ProductItem', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    product_id: INTEGER,
    name: STRING(100),
    price: {
      type: DECIMAL(10, 2),
      defaultValue: 0,
      get() {
        return formatAmount(this.getDataValue('price'))
      }
    },
    cost_price: {
      type: DECIMAL(10, 2),
      defaultValue: 0,
      get() {
        return formatAmount(this.getDataValue('cost_price'))
      }
    },
    thumbnail: STRING(255),
    description: TEXT,
    images: TEXT,
    spec: STRING,
    stock: { type: INTEGER, defaultValue: 0 },
    sales: { type: INTEGER, defaultValue: 0 },
    status: { type: INTEGER, defaultValue: 1 },
    create_time: {
      type: DATE,
      defaultValue: new Date(),
      get() {
        return formatDate(this.getDataValue('create_time'))
      }
    },
    update_time: {
      type: DATE,
      defaultValue: new Date(),
      get() {
        return formatDate(this.getDataValue('update_time'))
      }
    },
  },{
    tableName: 'product_item',
    timestamps: true, // 启用时间戳(createdAt, updatedAt)
    updatedAt: 'update_time', // 不想要 updatedAt
    createdAt: 'create_time', // 想要  createdAt 但是希望名称叫做 create_time
  });

  Product.associate = function() {
    app.model.ProductItem.belongsTo(app.model.Product, { foreignKey: 'product_id', as: 'product' });
  };

  return Product;
};
